
package com.winning.sx.microframework.controller.busi;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.winning.dapi.data.entity.DataTable;
import com.winning.sx.microframework.common.util.Constains;
import com.winning.sx.microframework.common.util.FileTools;
import com.winning.sx.microframework.common.util.SqlTool;
import com.winning.sx.microframework.model.exception.CustomException;
import com.winning.sx.microframework.model.manage.LoginSession;
import com.winning.sx.microframework.model.message.AjaxDataResponseMessage;
import com.winning.sx.microframework.model.message.AjaxTableResponseMessage;
import com.winning.sx.microframework.service.EasyService;
import com.winning.sx.microframework.service.base.EquipmentService;
import com.winning.sx.microframework.service.base.MessageService;
import com.winning.sx.microframework.service.sysmanage.ConstService;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/busi/equipment/Handle")
public class EquipmentMaintainHandleController {
    @Autowired
    EasyService easyService;
    @Autowired
    ConstService service;
    @Autowired
    MessageService messageService;
    @Autowired
    EquipmentService equipmentService;
    @Autowired
    ConstService constService;

    @RequestMapping(value = {"/", ""})
    public ModelAndView init() throws IOException, CustomException, SQLException {
        ModelAndView mv = new ModelAndView("/busi/equipmentMaintainHandle");
        List state = service.queryCount("201");
        mv.addObject("state", state);
        List brand = service.queryCount("300");
        mv.addObject("brand", brand);
        List way = service.queryCount("600");
        mv.addObject("way", way);
        List question = service.queryCount("110");
        mv.addObject("question", question);
        List dataType = service.queryCount("111");
        mv.addObject("dataType", dataType);
        List level = service.queryCount("114");
        mv.addObject("level", level);
        List repairState = service.queryCount("115");
        mv.addObject("repairState", repairState);

        Map eqRootClassP=new HashMap();
        eqRootClassP.put("superId","0");
        eqRootClassP.put("validFlag","100001");
        DataTable  eqRootClassS = easyService.queryList("BASE_EqClass",eqRootClassP);
        List eqRootClass = eqRootClassS.getDataRows();
        mv.addObject("eqRootClass", eqRootClass);

        Map map = new HashMap();
        List eqClass = easyService.querySql("SELECT " +
                "  c1.name + '-' + c2.name name, " +
                "  c2.code " +
                "FROM BASE_EqClass c1 " +
                "  RIGHT JOIN BASE_EqClass c2 ON c1.id = c2.superId " +
                "WHERE c2.validFlag = '100001' AND c1.id IS NOT NULL ",map).getDataRows();
        mv.addObject("eqClass", eqClass);
        LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
        Map<String,String> param=new HashMap();
        param.put("organizationType","400001");
        param.put("superOrganizationId",login.getOrgId());//全部客户的都展示，并不是展示中心自己的下属机构
        mv.addObject("organizationName", JSON.toJSON(service.queryMyOrg(param)).toString());

        //工单派发的内部机构
        param.put("organizationType","400002");
        param.put("superOrganizationId",login.getOrgId());
        mv.addObject("organizationInnerName", JSON.toJSON(service.queryMyOrg(param)).toString());

        return mv;
    }



    //工单配发查询
    @ResponseBody
    @RequestMapping(value = {"/queryWork"})
    public AjaxTableResponseMessage queryWork(String datas ) {
        AjaxTableResponseMessage ajaxTableResponseMessage = new AjaxTableResponseMessage();
        Map<String, String> param = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null)
            param = objectMapper.readValue(datas, Map.class);
            Map map=new HashMap();
            if (!"0".equals(param.get("organization"))) {
                String organization = param.get("organization").toString().trim().replaceAll(",","");
                map.put("organization", organization);
            }
            String sql="SELECT s.id, o.name AS organizationName, s.name AS staffName, COUNT(r.id) AS num" +
                    " , MIN(r.createTime) AS minTime, MAX(r.createTime) AS maxTime  " +
                    " FROM BASE_staff s  " +
                    " LEFT JOIN BASE_Organization o ON s.organizationId = o.id  " +
                    " LEFT JOIN (  " +
                    " SELECT *  " +
                    " FROM BUSI_RepairSubmitRecord b  " +
                    " WHERE submitType = '112003'  " +
                    " AND b.repairApplyId IN (  " +
                    " SELECT id  " +
                    " FROM BUSI_MaintenanceApplication m  " +
                    " WHERE m.state in ('201501','201402' ) " +
                    " )  " +
                    " ) r  " +
                    " ON s.id = r.toStaffId  where 1=1" +
                    (map.get("organization") != null ? (" and o.id='" + map.get("organization") + "'") : "") +
                    " GROUP BY s.id, o.name, s.name";
            DataTable all = easyService.querySql(sql,param);
            ajaxTableResponseMessage.setDatas(all.getDataRows());
            ajaxTableResponseMessage.setTotalSize((int) all.getTotalRowNum());
            ajaxTableResponseMessage.setSuccess(true);
        } catch (Exception e) {
            ajaxTableResponseMessage.setSuccess(false);
            ajaxTableResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxTableResponseMessage;
    }
    //工单配发
    @ResponseBody
    @RequestMapping(value = {"/saveWorkOrder"})
    @Transactional(propagation= Propagation.REQUIRED)
    public AjaxDataResponseMessage saveWorkOrder(String datas) {
        AjaxDataResponseMessage ajaxDataResponseMessage = new AjaxDataResponseMessage();
        Map<String, String> map = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null) {
                map = objectMapper.readValue(datas, Map.class);
                Map submit=new HashMap();
                submit.put("repairApplyId",map.get("repairApplyId").toString());
                submit.put("toStaffId",map.get("toStaffId").toString());
                submit.put("state",Constains.RepairSubmit_NEW);
                submit.put("handleType","无");//其实是 推荐维修方式
                submit.put("submitType","112003");
                LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
                submit.put("fromStaffId",login.getStaffId().toString());
                easyService.save("BUSI_RepairSubmitRecord", "id", submit);

                Map query = new HashMap();
                Map update = new HashMap();
                query.put("id", map.get("repairApplyId").toString());
                update.put("state", Constains.STATE_CENTERMESSAGE_DISTRIBUTE);
                easyService.update("BUSI_MaintenanceApplication", query, update);
                ajaxDataResponseMessage.setSuccess(true);

                //模板消息
                Map message=new HashMap();
                message.put("template",Constains.MESSAGE_TEMPLATE_3);
                message.put("staffId", map.get("toStaffId").toString());
                message.put("orgName",equipmentService.getOrgname(map.get("equipmentId").toString()).get("superName"));
                message.put("mFlowCode",map.get("mFlowCode").toString());
                message.put("eCode",map.get("eCode").toString());
                message.put("tel",map.get("telephone").toString());
                message.put("name",map.get("name").toString());
                message.put("type",constService.queryValue(map.get("eType").toString()));
                message.put("first","为您派发了新的维修单，请查收！");
                messageService.saveMessages(message);
            }
        } catch (Exception e) {
            ajaxDataResponseMessage.setSuccess(false);
            ajaxDataResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return ajaxDataResponseMessage;
    }

    @RequestMapping(value = {"/print/{id}"})
    public ModelAndView print(@PathVariable("id")String id) throws IOException, CustomException, SQLException {
        ModelAndView mv = new ModelAndView("/busi/printEquipmentMaintainHandle");
        Map map = new HashMap();
        //获取主要数据
        Map mainData = easyService.querySql("select m.*,sa.name applyStaffName,e.usePosition,e.name equipmentName,e.barCode equipmentCode,c1.name questionTypeName from BUSI_MaintenanceApplication m " +
                " left join BASE_Staff sa on m.applyStaffId=sa.id " +
                "  left join BASE_Equipment e on m.equipmentId=e.id " +
                "  left join BASE_Const c1 on c1.code=m.questionTypeCode " +
                "where m.id="+id,map).getDataRows().get(0);

        Map orgInfo=equipmentService.getOrgname(mainData.get("equipmentId").toString());

        //获取派单数据

        Map submitRecord = easyService.querySql("select r.*,s.name toStaffName,s.telephone from BUSI_RepairSubmitRecord r " +
                "left join BASE_Staff s on r.toStaffId=s.id " +
                "where  r.submitType='112003' " +
                "and r.repairApplyId="+id,map).getDataRows().get(0);

        //附件
        List supplementData = easyService.querySql("select *,c1.name dataTypeName from BUSI_RepairSupplement m " +
                "  left join BASE_Const c1 on c1.code=m.dataType " +
                "where m.repairApplyId="+id,map).getDataRows();

        mv.addObject("supplementData", supplementData);
        mv.addObject("mainData", mainData);
        mv.addObject("orgInfo", orgInfo);
        mv.addObject("submitRecord", submitRecord);
        mv.addObject("printTime", SqlTool.getNowTimeString2());
        return mv;
    }

    //维修结果
    @ResponseBody
    @RequestMapping(value = {"/saveMaintenance"})
    public AjaxDataResponseMessage maintenance(String datas) {
        AjaxDataResponseMessage ajaxDataResponseMessage = new AjaxDataResponseMessage();
        Map<String, String> map = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null) {
                map = objectMapper.readValue(datas, Map.class);
                LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
                Map roleId=new HashMap();
                roleId.put("userId",login.getcUserID().toString());
                Map entity=easyService.queryEntity("PM_StaffAsUser",roleId);
                if(entity!=null){
                    map.put("maintenanceStaffId",entity.get("staffId").toString());
                }
                map.put("state","200001");
                easyService.save("BUSI_handleResult", "id", map);
                ajaxDataResponseMessage.setSuccess(true);
            }
        } catch (Exception e) {
            ajaxDataResponseMessage.setSuccess(false);
            ajaxDataResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxDataResponseMessage;
    }

}

